import {
  PlanListItem,
  PlanStatisticsSearchParams,
  planStudySituationList,
  postPlanStudySituationList,
} from '@/api/StatisticsApi';
import { useAppSelector } from '@/redux/store';
import { Button, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import type { YmColumnsType } from 'ym-design';
import { YmTable } from 'ym-design';
import { PersonStudyDetailModal, PersonStudyTableProps } from '../PersonStudyDetail';

type SearchValue = Partial<PlanStatisticsSearchParams>;
type TableRecord = PlanListItem;

type planLearTableProp = {
  /*
   * desc 1自己 2企业
   */
  type: number | string;
  enterpriseId: string;
};
export default function PlanLearnTable({ type = 1, enterpriseId }: planLearTableProp) {
  // 人员明细
  const personStudyRef = useRef<any>();
  // organizationType -  1: 协会; 0: 企业
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt);
  const [planItem, setPlanItem] = useState<PersonStudyTableProps>({
    finishState: undefined,
    planCourseId: undefined,
    cycleId: undefined,
    entId: '',
    enterpriseId: undefined,
  });
  const [refreshFlag, _setRefreshFlag] = useState(false);
  const [columns, setColumns] = useState<YmColumnsType<TableRecord>>();

  // 刷新table的 flag
  function refreshTable() {
    _setRefreshFlag((v) => !v);
  }

  useEffect(() => {
    const columnsData: YmColumnsType<TableRecord> = [
      {
        title: '编号',
        dataIndex: 'No',
        key: 'No',
        width: 80,
        fixed: 'left',
        render(value) {
          return value < 10 ? '0' + value : value;
        },
      },
      {
        title: '计划名称',
        dataIndex: 'name',
        key: 'name',
        width: 220,
        ellipsis: true,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100,
        ellipsis: true,
        render: (text, record) => <span>{text == '200' ? `每${record.cycleTime}日一学` : '固定时间'} </span>,
      },
      {
        title: '周期',
        dataIndex: 'cycleTime',
        key: 'cycleTime',
        width: 250,
        ellipsis: true,
        render: (text, record) => <span>{record.startTime + '至' + record.endTime} </span>,
      },
      {
        title: '应学人数(人)',
        dataIndex: 'allPersonNum',
        key: 'allPersonNum',
        width: 115,
      },
      {
        title: '已学人数(人)',
        dataIndex: 'studyPersonNum',
        key: 'studyPersonNum',
        width: 115,
      },
      {
        title: '未学人数(人)',
        dataIndex: 'noStudyPersonNum',
        key: 'noStudyPersonNum',
        width: 115,
        render: (text, record) => (
          <Button
            type="text"
            size="small"
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation();

              setPlanItem({
                finishState: 2,
                planCourseId: record.planCourseId || '',
                cycleId: record.cycleId || undefined,
                entId: entId,
                enterpriseId,
              });

              personStudyRef.current?.showModal();
            }}
          >
            <span className="safe-edu_table_operation_text">{text}</span>
          </Button>
        ),
      },
      {
        title: '已学率(%)',
        dataIndex: 'studyRatio',
        key: 'studyRatio',
        width: 100,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
        render: (text, record) => {
          return (
            <Space direction="horizontal" size={0}>
              <Button
                type="text"
                size="small"
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation();

                  setPlanItem({
                    finishState: '',
                    planCourseId: record.planCourseId || '',
                    cycleId: record.cycleId || undefined,
                    entId,
                    enterpriseId,
                  });

                  personStudyRef.current?.showModal();
                }}
              >
                <span className="safe-edu_table_operation_text">详情</span>
              </Button>
            </Space>
          );
        },
      },
    ];
    setColumns(columnsData);
    refreshTable();
  }, [type, enterpriseId]);

  return (
    <>
      <div className="plan-learn-table" style={{ height: '620px' }}>
        {columns ? (
          <YmTable<TableRecord, SearchValue>
            rowKey="planCourseId"
            columns={columns}
            toolBar={false}
            request={async ({ page }) => {
              let response;

              if (organizationType === 1) {
                response = await planStudySituationList({ entId }, page?.pageIndex, page?.pageSize);
              } else {
                response = await postPlanStudySituationList({
                  entId: enterpriseId,
                  curEntId: entId,
                  pageNum: page?.pageIndex,
                  pageSize: page?.pageSize,
                });
              }

              return response;
            }}
            requestOptions={{
              reFreshDep: [refreshFlag, enterpriseId],
            }}
          />
        ) : null}
      </div>
      <PersonStudyDetailModal props={planItem} innerRef={personStudyRef} onChange={() => {}} />
    </>
  );
}
